package com.example.seh.home;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.seh.R;
import com.example.seh.constant.Constant;
import com.example.seh.home.secondhand.Goods;
import com.example.seh.home.secondhand.GoodsDTO;
import com.example.seh.home.secondhand.GoodsDetailActivity;
import com.example.seh.home.secondhand.GoodsGridAdapter;
import com.example.seh.home.substitution.CourierDetailActivity;
import com.example.seh.home.substitution.CourierListAdapter;
import com.example.seh.home.substitution.CourierSuccessActivity;
import com.example.seh.home.substitution.DeliverDTO;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment {
    private TextView select;
    private Banner banner;
    private List<Integer> bannerData;
    private GridView gridGoods;
    private List<Goods> goods;
    private List<GoodsDTO> goodsDTOS = new ArrayList<>();
    private ImageButton exchange;
    private ListView listCourier;
    private List<DeliverDTO> couriers = new ArrayList<>();
    private boolean isGrid = true;
    private GoodsGridAdapter goodsAdapter;
    private CourierListAdapter courierAdapter;
    private SmartRefreshLayout smartRefreshLayout;
    private Spinner spinnerPark;
    private Spinner spinnerPrice;
    private Spinner spinnerTime;
    private Spinner spinnerPark2;
    private Spinner spinnerPrice2;
    private Spinner spinnerTime2;
    private Spinner spinnerAddress;
    private String park = "不限园区";
    private String price = "不限价格";
    private String time = "不限时间";
    private String park2 = "不限地点";
    private String price2 = "不限价格";
    private String time2 = "不限时间";
    private String address = "不限园区";
    private LinearLayout selectSpinnerLayout;
    private LinearLayout second_spinner;
    private LinearLayout errand_spinner;

    private boolean isFirst = true;

    private int currentNum = 1;
    private int currentNum2 = 1;
    private int currentNum3 = 1;
    private int currentNum4 = 1;
    private boolean isRefresh = true;
    private boolean isRefresh2 = true;
    private boolean isFirstLoad = true;
    private boolean isSelected = false;
    private boolean isSelected2 = false;

    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    goodsAdapter.notifyDataSetChanged();
                    if (!isRefresh) {
                        smartRefreshLayout.finishLoadMore();
                    } else {
                        smartRefreshLayout.finishRefresh();
                    }
                    break;
                case 2:
                    courierAdapter.notifyDataSetChanged();
                    if (!isRefresh2) {
                        smartRefreshLayout.finishLoadMore();
                    } else {
                        smartRefreshLayout.finishRefresh();
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        initData(view);//获取控件


        selectSpinner();//下拉框选择


        setListener();//上拉加载和下拉刷新

        //------------------------轮播图----------------------------
        initBannerData();//初始化轮播图数据
        banner.setAdapter(new BannerImageAdapter<Integer>(bannerData) {
            @Override
            public void onBindView(BannerImageHolder holder, Integer data, int position, int size) {
                //holder.imageView.setImageResource(data);
                Glide.with(getContext())
                        .load(data)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(holder.imageView);
            }
        });//轮播图adapter
        // 开启循环轮播
        banner.isAutoLoop(true);
        banner.setIndicator(new CircleIndicator(getContext()));
        banner.setScrollBarFadeDuration(1000);
        // 设置指示器颜色(TODO 即选中时那个小点的颜色)
        banner.setIndicatorSelectedColor(Color.GREEN);
        // 开始轮播
        banner.start();

        //------------------------搜索框----------------------------
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SelectActivity.class);
                startActivity(intent);
            }
        });


        //------------------------gridview----------------------------
        initGridData();//初始化grid数据
        //sendBackendRequest();
        goodsAdapter = new GoodsGridAdapter(
                getContext(),
                goodsDTOS,
                R.layout.goods_grid_item
        );
        gridGoods.setAdapter(goodsAdapter);
        setItemOnClick();//设置点击进入详情页

        //------------------------exchange----------------------------
        exchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isGrid) {
                    isGrid = false;
                    changToList();
                } else {
                    isGrid = true;
                    isFirstLoad = false;
                    changToGrid();
                }
            }
        });
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();

//    @Override
//    public void onResume() {
//        super.onResume();

//        if (!isFirst) {
//            sendBackendRequest();
//            Message message = new Message();
//            if (isGrid) {
//                Log.e("home", "onresume running");
//                message.what = 1;
//            } else {
//                message.what = 2;
//            }
//            handler.sendMessage(message);
//        }

        isFirst = false;

    }

//        isFirst = false;
//
//    }


    private void setListener() {
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (isGrid && !isSelected){
                    Log.e("二手","初始化刷新");
                    goodsDTOS.clear();
                    isRefresh = true;
                    currentNum = 1;
                    initGridData();
                }else if (!isGrid && !isSelected2){
                    Log.e("跑腿","初始化刷新");
                    couriers.clear();
                    isRefresh2 = true;
                    currentNum2 = 1;
                    initListData();
                }else if (isGrid && isSelected){
                    Log.e("二手","下拉框选择刷新");
                    goodsDTOS.clear();
                    isRefresh = true;
                    currentNum3 = 1;
                    sendBackendRequest();
                }else if (!isGrid && isSelected2){
                    Log.e("跑腿","下拉框选择刷新");
                    couriers.clear();
                    isRefresh2 = true;
                    currentNum4 = 1;
                    sendBackendRequest();
                }

            }
        });

        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isGrid && !isSelected){
                    Log.e("二手","初始化加载更多");
                    isRefresh = false;
                    currentNum++;
                    initGridData();
                }else if (!isGrid && !isSelected2){
                    Log.e("跑腿","初始化加载更多");
                    isRefresh2 = false;
                    currentNum2++;
                    initListData();
                }
                else if (isGrid && isSelected){
                    Log.e("二手","下拉框加载更多");
                    isRefresh = false;
                    currentNum3 ++;
                    sendBackendRequest();
                }else if (!isGrid && isSelected2){
                    Log.e("跑腿","下拉框加载更多");
                    isRefresh2 = false;
                    currentNum4 ++;
                    sendBackendRequest();
                }

            }
        });

    }

    private void selectSpinner() {
        spinnerPark.setSelection(0, true);
        spinnerPark.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                park = parent.getItemAtPosition(position).toString();
                isSelected = true;
                currentNum3 = 1;
                goodsDTOS.clear();
                isRefresh = true;
                sendBackendRequest(); // 向后台发送请求


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerPrice.setSelection(0, true);
        spinnerPrice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                price = parent.getItemAtPosition(position).toString();
                currentNum3 = 1;
                isSelected = true;
                goodsDTOS.clear();
                isRefresh = true;
                sendBackendRequest(); // 向后台发送请求

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerTime.setSelection(0, true);
        spinnerTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                time = parent.getItemAtPosition(position).toString();
                currentNum3 = 1;
                isSelected = true;
                goodsDTOS.clear();
                isRefresh = true;
                sendBackendRequest(); // 向后台发送请求

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerPark2.setSelection(0, true);
        spinnerPark2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                address = parent.getItemAtPosition(position).toString();
                isSelected2 = true;
                currentNum4 = 1;
                couriers.clear();
                isRefresh2 = true;
                sendBackendRequest(); // 向后台发送请求


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerPrice2.setSelection(0, true);
        spinnerPrice2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                price2 = parent.getItemAtPosition(position).toString();
                isSelected2 = true;
                currentNum4 = 1;
                couriers.clear();
                isRefresh2 = true;
                sendBackendRequest(); // 向后台发送请求


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerTime2.setSelection(0, true);
        spinnerTime2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                time2 = parent.getItemAtPosition(position).toString();
                isSelected2 = true;
                currentNum4 = 1;
                couriers.clear();
                isRefresh2 = true;
                sendBackendRequest(); // 向后台发送请求


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerAddress.setSelection(0, true);
        spinnerAddress.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                park2 = parent.getItemAtPosition(position).toString();
                currentNum4 = 1;
                isSelected2 = true;
                couriers.clear();
                isRefresh2 = true;
                sendBackendRequest(); // 向后台发送请求


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void sendBackendRequest() {

        OkHttpClient okHttpClient = new OkHttpClient();
        if (isGrid) {
//            goodsDTOS = new ArrayList<>();
            Request request = new Request.Builder()
                    .get()
                    .url(Constant.SELECT_SECOND + "addressName=" + park + "&price=" + price + "&publishTime=" + time + "&pageIndex=" +currentNum3)
                    .build();
            Log.e("地址：", request.url().toString());
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("okhttp", "获取数据失败");
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String goodsStr = jsonObject.getString("data");

                            Gson gson = new Gson();
                            Type type = new TypeToken<List<GoodsDTO>>() {
                            }.getType();
                            List<GoodsDTO> list = gson.fromJson(goodsStr, type);
                            if (isRefresh){
                                goodsDTOS.clear();
                            }
                            goodsDTOS.addAll(list);
                        if (goodsStr.equals("[]")){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), "数据加载完了哦~", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } else {
//            couriers = new ArrayList<>();
            Request request = new Request.Builder()
                    .get()
                    .url(Constant.SELECT_ERRAND + "addressName=" + park2 + "&receiveName=" + address + "&price=" + price2 + "&publishTime=" + time2 + "&pageIndex="+currentNum4)
                    .build();
            Log.e("地址：", request.url().toString());
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("okhttp", "获取数据失败");
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    System.out.println(result);

                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String courierStr = jsonObject.getString("data");

                            System.out.println(courierStr);
                            Gson gson = new Gson();
                            Type type = new TypeToken<List<DeliverDTO>>() {
                            }.getType();
                            List<DeliverDTO> list = gson.fromJson(courierStr, type);
                            System.out.println("couriers:" + list.toString());
                            if (isRefresh2){
                                couriers.clear();
                            }
                            couriers.addAll(list);
                        if (courierStr.equals("[]")){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), "数据加载完了哦~", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        }


    }

    private void setItemOnClick() {
        gridGoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
                intent.putExtra("goods", goodsDTOS.get(position));
                startActivity(intent);
            }
        });
        listCourier.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), CourierDetailActivity.class);
                intent.putExtra("couriers", couriers.get(position));
                Log.e("deliver", couriers.get(position).toString());
                startActivity(intent);
            }
        });
    }

    private void changToGrid() {
        listCourier.setVisibility(View.INVISIBLE);
        gridGoods.setVisibility(View.VISIBLE);
        errand_spinner.setVisibility(View.GONE);
        second_spinner.setVisibility(View.VISIBLE);

        if (!isSelected){
            currentNum = 1;
            goodsDTOS.clear();
            initGridData();
        }else {
            sendBackendRequest();//初始化grid数据
        }

        goodsAdapter = new GoodsGridAdapter(
                getContext(),
                goodsDTOS,
                R.layout.goods_grid_item
        );
        gridGoods.setAdapter(goodsAdapter);
    }

    private void changToList() {
        //------------------------listview----------------------------
        gridGoods.setVisibility(View.INVISIBLE);
        listCourier.setVisibility(View.VISIBLE);
        errand_spinner.setVisibility(View.VISIBLE);
        second_spinner.setVisibility(View.GONE);
        if (!isSelected2) {
            currentNum2 = 1;
            couriers.clear();
            initListData();
        } else {
            sendBackendRequest();//初始化list数据
        }

        courierAdapter = new CourierListAdapter(
                getContext(),
                couriers,
                R.layout.courier_list_item
        );
        listCourier.setAdapter(courierAdapter);
    }

    private void initListData() {
//        couriers = new ArrayList<>();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(Constant.FINDALLCOURIER+"/"+currentNum2)
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                System.out.println(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String courierStr = jsonObject.getString("data");

                        System.out.println(courierStr);
                        Gson gson = new Gson();
                        Type type = new TypeToken<List<DeliverDTO>>() {
                        }.getType();
                        List<DeliverDTO> list = gson.fromJson(courierStr, type);
                        System.out.println("couriers:" + list.toString());
                        couriers.addAll(list);
                    if (courierStr.equals("[]")){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "数据加载完了哦~", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void initGridData() {
        //goodsDTOS = new ArrayList<>();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                //.url(Constant.FINDALLGOODS + "/1")
                .url(Constant.FINDALLGOODS + "/" + currentNum)
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                System.out.println(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String goodsStr = jsonObject.getString("data");

                        Gson gson = new Gson();
                        Type type = new TypeToken<List<GoodsDTO>>() {
                        }.getType();
                        List<GoodsDTO> list = gson.fromJson(goodsStr, type);

                        goodsDTOS.addAll(list);
                    if (goodsStr.equals("[]")){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "数据加载完了哦~", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void initBannerData() {
        bannerData = new ArrayList<>();
        bannerData.add(R.drawable.banner6);
        bannerData.add(R.drawable.banner5);
        bannerData.add(R.drawable.banner8);
        bannerData.add(R.drawable.banner7);
    }

    private void initData(View view) {
        select = view.findViewById(R.id.select);
        banner = view.findViewById(R.id.banner);
        gridGoods = view.findViewById(R.id.grid_good);
        exchange = view.findViewById(R.id.exchange);
        listCourier = view.findViewById(R.id.list_courier);
        smartRefreshLayout = view.findViewById(R.id.home_srl);

        selectSpinnerLayout = view.findViewById(R.id.select_spinner);
        second_spinner = selectSpinnerLayout.findViewById(R.id.second_spinner_button);
        errand_spinner = selectSpinnerLayout.findViewById(R.id.errand_spinner_button);

        spinnerPark = view.findViewById(R.id.spinner_park);
        ArrayAdapter<CharSequence> parkAdapter = ArrayAdapter.createFromResource(
                getContext(),
                R.array.park_array,
                android.R.layout.simple_spinner_item
        );
        parkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerPark.setAdapter(parkAdapter);

        spinnerPrice = view.findViewById(R.id.spinner_price);
        ArrayAdapter<CharSequence> priceAdapter = ArrayAdapter.createFromResource(
                getContext(),
                R.array.price_array,
                android.R.layout.simple_spinner_item
        );
        priceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerPrice.setAdapter(priceAdapter);

        spinnerTime = view.findViewById(R.id.spinner_time);
        ArrayAdapter<CharSequence> timeAdapter = ArrayAdapter.createFromResource(
                getContext(),
                R.array.time_array,
                android.R.layout.simple_spinner_item
        );
        timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTime.setAdapter(timeAdapter);

        spinnerPark2 = view.findViewById(R.id.spinner_park2);
        ArrayAdapter<CharSequence> parkAdapter2 = ArrayAdapter.createFromResource(
                getContext(),
                R.array.park_array,
                android.R.layout.simple_spinner_item
        );
        parkAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerPark2.setAdapter(parkAdapter2);

        spinnerPrice2 = view.findViewById(R.id.spinner_price2);
        ArrayAdapter<CharSequence> priceAdapter2 = ArrayAdapter.createFromResource(
                getContext(),
                R.array.price_array,
                android.R.layout.simple_spinner_item
        );
        priceAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerPrice2.setAdapter(priceAdapter2);

        spinnerTime2 = view.findViewById(R.id.spinner_time2);
        ArrayAdapter<CharSequence> timeAdapter2 = ArrayAdapter.createFromResource(
                getContext(),
                R.array.time_array,
                android.R.layout.simple_spinner_item
        );
        timeAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTime2.setAdapter(timeAdapter2);


        spinnerAddress = view.findViewById(R.id.spinner_address);
        ArrayAdapter<CharSequence> addressAdapter = ArrayAdapter.createFromResource(
                getContext(),
                R.array.address_array,
                android.R.layout.simple_spinner_item
        );
        addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerAddress.setAdapter(addressAdapter);
    }

}